<script setup lang="ts">
import {type PropType, ref,h} from "vue";
import type {FormInstance, FormRules} from "element-plus";
import  {type ElFormItem,COMPONENT_MAP} from "./types";

const props = defineProps({
  rules:Object as PropType<FormRules<any>>,
  inline:{
    type: Boolean,
    default:false,
  },
  'label-position':{
    type: String as PropType<'left' | 'right' | 'top'>,
    default:'top',
  },
  'label-width':{
    type: [Number,String],
    default:'100px'
  },
  'label-suffix':{
    type: String,
    default:":"
  },
  size:{
    type: String as PropType<'' | 'large' | 'default' | 'small'>,
    default:'large'
  },
  'scroll-to-error':{
    type:Boolean,
    default:true
  },
  formItems:{
    type:Array as PropType<ElFormItem[]>,
    required:false
  },
  useFooter:{
    type: Boolean,
    default: true
  }
});
const emits = defineEmits<{
  (e:'ok',res?:any):void,
  (e:'cancel'):void,
}>();
const show=ref(false)
const formData=ref<any>({})
const formIns=ref<FormInstance>()
const renderCom=(e:ElFormItem)=>{
  return e?.component?COMPONENT_MAP[e.component]:h('div')
}
const cancel=()=>{
  formData.value={}
  emits('cancel')
}
const ok=()=>{
  formIns.value?.validate().then(()=>{
    emits('ok',formData.value)
  }).catch(()=>{})
}
const setForm=(f:any)=>{
  formData.value=f;
}
const getForm=()=>{
  return formData.value
}
defineExpose({
  setForm,
  getForm,
})
</script>

<template>
  <div class="form-core">
    <!-- 关键：阻止默认提交 -->
    <el-form @submit.prevent class="form-ins" ref="formIns" :model="formData" v-bind="props">
      <el-form-item v-for="e in props.formItems" v-bind="e" :key="e.prop">
        <template v-if="e.slot">
          <slot :name="e.slot" :formData="formData"></slot>
        </template>
        <template v-else-if="e.component">
          <component style="width: 100%" :is="renderCom(e)" v-model="formData[e.prop]" v-bind="e.props"/>
        </template>
      </el-form-item>
    </el-form>
    <div class="footer" v-if="useFooter">
      <el-button link @click="cancel">取消</el-button>
      <el-button link type="primary" @click="ok">确定</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.form-core{
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .form-ins{
    flex: 1;
  }
  .footer{
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 100%;
  }
}
</style>
